package com.huanlis.consumer.config;


import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.Objects;

/**
 * 数据库自动填充
 */

@Component
@Slf4j
public class MybatisAutoFillConfig implements MetaObjectHandler {

    /**
     * 处理mybatis新增字段填充
     *
     * @author lihuan
     * @since 2023/11/15 16:18
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Object updateTime = this.getFieldValByName("updateTime", metaObject);
        if (Objects.isNull(updateTime)) {
            Class<?> updateTimeType = metaObject.getGetterType("updateTime" );
            if (updateTimeType == LocalDateTime.class) {
                this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
            }
            if (updateTimeType == Date.class) {
                this.setFieldValByName("updateTime", new Date(), metaObject);
            }
        }
        Object createTime = this.getFieldValByName("createTime", metaObject);
        if (Objects.isNull(createTime)) {
            Class<?> updateTimeType = metaObject.getGetterType("createTime" );
            if (updateTimeType == LocalDateTime.class) {
                this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
            }
            if (updateTimeType == Date.class) {
                this.setFieldValByName("createTime", new Date(), metaObject);
            }
        }

    }

    /**
     * 处理mybatis更新字段填充
     *
     * @author lihuan
     * @since 2023/11/15 16:18
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Object updateTime = this.getFieldValByName("updateTime", metaObject);
        if (Objects.isNull(updateTime)) {
            Class<?> updateTimeType = metaObject.getGetterType("updateTime" );
            if (updateTimeType == LocalDateTime.class) {
                this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
                this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
            }
            if (updateTimeType == Date.class) {
                this.setFieldValByName("updateTime", new Date(), metaObject);
                this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
            }
        }
    }

}
